// 导入 card组件
import { Form, Input, Button, Checkbox, Card } from 'antd'
// 图片资源
import logo from '@/assets/logo.png'
import './index.scss'
import { useHistory } from 'react-router-dom'
// 导入 redux的hook
import { useDispatch } from 'react-redux'
// 导入actionCreator
import { loginAction } from '@/store/actions/login'

const Login = () => {
  // 生成history的hook
  const history = useHistory()
  // dispatch的hook
  const dispatch = useDispatch()

  // values是个对象 属性名和 formItem的name
  const onFinish = async (values) => {
    const { mobile, code } = values
    // 触发action
    await dispatch(loginAction({ mobile, code }))
    // 去首页
    history.push('/')
  }

  // 校验失败
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }

  // 手机号校验规则
  const mobileRules = [
    { required: true, message: '手机号不能为空' },
    { pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/, message: '手机号格式有误' },
  ]
  // 验证码的校验规则
  const codeRules = [
    { required: true, message: '验证码不能为空' },
    { max: 6, min: 3, message: '验证码的长度应该为3-6位' },
  ]
  // 是否同意的校验规则
  const agreeRules = [
    {
      validator: (_, value) => {
        console.log('_:', _) // 字段的信息
        console.log('value:', value) // 字段的值
        // value是否为真 ，真->成功,假，失败
        return value ? Promise.resolve() : Promise.reject(new Error('请勾选用户协议！'))
      },
    },
  ]
  return (
    <div className='login'>
      {/* 容器盒子 */}
      <Card className='login-container'>
        {/* 图片资源 */}
        <img className='login-logo' src={logo} alt='' />
        {/* 登录表单
          1. labelCol 左侧文本的宽度，如果有的话
          2. wrapperCol 表单整体的宽度，100%是24
          3. validateTrigger 设置触发的时机   onChange改变  onBlur失去焦点
         */}
        <Form
          name='basic'
          validateTrigger={['onChange', 'onBlur']}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 24 }}
          initialValues={{ mobile: '13911111111', code: '246810', agree: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item name='mobile' rules={mobileRules}>
            <Input placeholder='请输入你的手机号' />
          </Form.Item>

          <Form.Item name='code' rules={codeRules}>
            <Input placeholder='请输入验证码' />
          </Form.Item>

          <Form.Item name='agree' valuePropName='checked' rules={agreeRules} wrapperCol={{ span: 24 }}>
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button size='large' block type='primary' htmlType='submit'>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
